package com.tanhua.mongo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.VO.PageResult;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.mongo.utils.IdWorker;
import com.tanhua.mongo.utils.TimeLineService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
*@auther ll
*@date 2022/3/29  9:07
*/
@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    //发布动态
    public void publish(Movement movement) {
        //1.保存动态详情
        try {
            //1.1设置pid
            movement.setPid(idWorker.getNextId("movement"));
            //1.2设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);  //保存
//            //2.查询当前用户的好友数据   根据id查询
//            Criteria criteria = Criteria.where("userid").is(movement.getUserId());
//            Query query = Query.query(criteria);
//            //查询出当前用户的所有好友
//            List<Friend> friends = mongoTemplate.find(query, Friend.class);
//            //3.循环好友数据，构建时间线数据存入数据库
//            for (Friend friend : friends) {
//                MovementTimeLine timeLine = new MovementTimeLine();
//                timeLine.setMovementId(movement.getId());  //动态id
//                timeLine.setUserId(friend.getUserId());     //当前用户id
//                timeLine.setFriendId(friend.getFriendId());   //可见好友id
//                timeLine.setCreated(System.currentTimeMillis());  //当前时间
//                mongoTemplate.save(timeLine);
//            }
            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //查看个人动态  mongo分页的写法
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0l,movements);
    }

    /**
     *查询当前用户好友发布的所有动态
     * @param friendId 当前造作用户id
     */
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {
        //1.根据friendId查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lineList = mongoTemplate.find(query, MovementTimeLine.class);
        //2.提取动态id
        List<ObjectId> movementIds = CollUtil.getFieldValues(lineList, "movementId", ObjectId.class);
        //3.根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(movementIds));
        return mongoTemplate.find(movementQuery,Movement.class);
    }

    //随机获取多条动态数据
    public List<Movement> rondomMovements(Integer counts) {
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(counts));

        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation,Movement.class);

        return movements.getMappedResults();
    }

    //根据pid数组查询动态
    public List<Movement> finfMovementsByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pId").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

}
